//
//  FeedDetailViewController.m
//  NewsReader
//
//  Created by blacksun on 10-11-10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "FeedDetailViewController.h"
#import "Feed.h"
#import "Content.h"
#import "SqlUtil.h"
#import "NewsReaderAppDelegate.h"
#import "FeedDetailWithWebviewController.h"

@implementation FeedDetailViewController


@synthesize container,titleLabel,pubDateLabel,authorLable,feed,inPressImageDownloaders,loadingView;
@synthesize announceView;
@synthesize aTableView;
@synthesize sendTweetController;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    //给图片加圆角
	self.aTableView.layer.cornerRadius = 6;
	self.aTableView.layer.masksToBounds = YES;

	[self.announceView removeFromSuperview];
    [self.container removeFromSuperview];
    self.aTableView.tableHeaderView = self.container;
    
	self.inPressImageDownloaders = [NSMutableDictionary dictionary];
	
	self.aTableView.allowsSelection = NO;
			
}
-(void)removeDetail{
	displayed = NO;
	self.aTableView.tableFooterView = nil;
	self.feed.details = nil;
	[self.aTableView reloadData];
	[self stopAllImageDownloading];
	self.loadingView.hidden = NO;
	
	self.sendTweetController = nil;
	
}
-(void)reset:(Feed *)aFeed{
	self.feed = aFeed;
	self.titleLabel.text = self.feed.title;
	self.pubDateLabel.text = self.feed.pubDate;
	self.authorLable.text = self.feed.author;
	
	[self removeDetail];
}
-(void)displayDetail{
	if (displayed) {
		return;
	}
	displayed = YES;
	
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	networkState = delegate.networkState;
	User *user = delegate.user;
	if (!user.optimizeContent) {
		UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0.0, 70.0, 300.0, 360.0)];
		NSString * urlStr = [[NSString alloc] initWithFormat:@"%@",self.feed.link];
		NSURL *url = [[NSURL alloc] initWithString:urlStr];
		NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
		[self.container addSubview:webView];
		[webView loadRequest:request];
		[webView release];
		[request release];
		[url release];
		[urlStr release];
		return;
	}
	
	if (self.feed.details == nil || [self.feed.details count] == 0) {
		self.feed.details = [SqlUtil selectContentsWithFeed:self.feed];
				
	}
	self.aTableView.tableFooterView =self.announceView;
	[aTableView reloadData];

	self.loadingView.hidden = YES;
}

- (void)didReceiveMemoryWarning {
	[self stopAllImageDownloading];
    [super didReceiveMemoryWarning];
}

-(IBAction) popController{
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	[delegate.navigationController popViewControllerAnimated:YES];
}

-(void)startIconDownload:(NSString *)aImageUrl identify:(NSIndexPath *)identify{
    if ([self.inPressImageDownloaders objectForKey:identify])
        return;
	ImageDownloader *imageDownloader = [[ImageDownloader alloc] init];
	imageDownloader.imageUrl = aImageUrl;
	imageDownloader.identifier = identify;
	imageDownloader.delegate = self;
	[imageDownloader startDownload];
	[self.inPressImageDownloaders setObject:imageDownloader forKey:identify];
	[imageDownloader release];
}

- (void)imageLoaded:(UIImage *)image forIdentify:(NSObject *)identifier{
	if (!image) return;
	NSIndexPath *indexPath = (NSIndexPath *)identifier;
	UITableViewCell *cell = [aTableView cellForRowAtIndexPath:indexPath];
	UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:kDetailCell_Image];
	imageView.image = image;
	Content *content = [self.feed.details objectAtIndex:[indexPath row]];
	content.image = image;
	[self.inPressImageDownloaders removeObjectForKey:identifier];
}

-(void) stopAllImageDownloading{
	
	NSArray *allDownloads = [self.inPressImageDownloaders allValues];
    [allDownloads makeObjectsPerformSelector:@selector(cancelDownload)];
	[self.inPressImageDownloaders removeAllObjects];
}

-(IBAction) gotoSafari:(id)sender{
	FeedDetailWithWebviewController *webViewController = [[FeedDetailWithWebviewController alloc] initWithNibName:@"FeedDetailWithWebviewViewController" bundle:nil];
	webViewController.feed = self.feed;
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	[delegate.navigationController pushViewController:webViewController animated:YES];
	[webViewController release];
	
}

- (void)dealloc {
	[self stopAllImageDownloading];
	[self.inPressImageDownloaders release];
	[self.announceView release];
	[self.loadingView release];
	[self.titleLabel release];
	[self.pubDateLabel release];
	[self.authorLable release];
	[self.feed release];
	[self.container release];
	self.aTableView = nil;
	self.sendTweetController = nil;
    [super dealloc];
	
}



#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	NSInteger size = [self.feed.details count];
	
    return size;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)atableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *FeedListCellIdentifier = @"FeedDetailTable";
    
	UITableViewCell *cell = [atableView dequeueReusableCellWithIdentifier:FeedListCellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:FeedListCellIdentifier] autorelease];
		UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, 100.0, 200.0)];
		imageView.tag =	kDetailCell_Image;
		[cell.contentView addSubview:imageView];
		[imageView release];
		
		UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 9.0, 50.0, 100.0)];
		label.tag = kDetailCell_Label;
		label.numberOfLines = 0;
		label.lineBreakMode = UILineBreakModeWordWrap;
		label.font = [UIFont systemFontOfSize:kFontSize];
		label.textColor = [UIColor darkGrayColor];//[UIColor colorWithRed:30/255.0 green:30/255.0 blue:30/255.0 alpha:1.0];
		[cell.contentView addSubview:label];
		[label release];
	}
	
	NSInteger row = [indexPath row];
	UILabel *label = (UILabel *)[cell.contentView viewWithTag:kDetailCell_Label];
	UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:kDetailCell_Image];
	label.text = nil;
    label.hidden = NO;
	imageView.image = nil;
    imageView.hidden = NO;
	
	Content *content = [self.feed.details objectAtIndex:row];
	if ([content.type isEqualToString:kContentTypeText]) {
		label.frame = CGRectMake(20.0, 0.0, 260.0, content.heigth);
		label.text = content.content;
        imageView.hidden = YES;
	}else if (!networkState) {
		//do nothing	
	}else{
        label.hidden = YES;
		NSInteger width = content.width/2;
		if (width/2>240) {
			width = 240;
		}
		imageView.frame = CGRectMake((300-width)/2, 10.0, width, content.heigth/2);
		if (!content.image){
			if (atableView.decelerating == NO) {
				[self startIconDownload:content.content identify:indexPath];
			}
            imageView.image = [UIImage imageNamed:@"detail_loading.png"];                
        }
        else{
			imageView.image = content.image;
        }
	}

	
	return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	NSInteger row = [indexPath row];
	
	Content *content = [self.feed.details objectAtIndex:row];
	if ([content.type isEqualToString:kContentTypeText]) {
		CGSize constraint = CGSizeMake(260.0, 20000.0);
		CGSize size = [content.content sizeWithFont:[UIFont systemFontOfSize:kFontSize] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
		content.heigth = size.height;
		return content.heigth+15.0;
	}else if (!networkState) {//如果是图片且网络不可用
		return 20.0;
	}else{
		return content.heigth/2+20;
	}
}


-(IBAction) share{
	UIActionSheet *sheet = [[[UIActionSheet alloc] initWithTitle:@"分享到微博" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"新浪微博",@"腾讯微博",nil] autorelease];
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
    UIViewController *controller = [delegate.navigationController visibleViewController];
    [sheet showInView:controller.view];
	//[sheet showFromToolbar:delegate.navigationController.toolbar];
	//[sheet release];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
	if (buttonIndex==2) {
		return;
	}
	
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	if (!delegate.networkState) {
		[HttpUtil showUsageAlertDialog];
        return;
	}
	WeiboOAuthController *oauthController = [[WeiboOAuthController alloc] init];
	BaseWeibo *weibo = nil;
	switch (buttonIndex) {
		case 0:{
			weibo = [[SinaWeibo alloc] init];
			break;
		}
		case 1:
			weibo = [[TencentWeibo alloc] init];
			break;
		default:
			break;
	}
	oauthController.weibo = weibo;

	
	if (weibo.oauthKey.tokenKey && weibo.oauthKey.tokenSecret) {//如果已经登录过，则直接到转发页面
		
		[self addSendTweetView:weibo];
	}else {//之前没有登录过，跳转到登录界面
		oauthController.parentContrpller = self;
		[delegate.navigationController pushViewController:oauthController animated:YES];
	}

	[weibo release];
	[oauthController release];
}

-(void) addSendTweetView:(BaseWeibo *)aWeibo{
	SendTweetController *controller = [[SendTweetController alloc] init];
	controller.weibo = aWeibo;
    controller.feed = self.feed;
	
	NSString *content = [[NSString alloc] initWithFormat:@"%@ %@",feed.title,feed.link];
	controller.content = content;
	[content release];
	
	controller.view.frame = CGRectMake(0.0, 460.0, 320.0, 460.0);
	[self.view addSubview:controller.view];
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.5f];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	[UIView setAnimationRepeatAutoreverses:NO];
	controller.view.frame = CGRectMake(0.0, 0.0, 320.0, 460.0);
	[controller.contentView becomeFirstResponder];
	[UIView commitAnimations];
	self.sendTweetController = controller;
	[controller setScrollAble:NO];
	[controller release];
}




@end
